package com.neusoft.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.neusoft.po.Credit;

@Mapper
public interface CreditMapper {
//	//增加积分实际是创建一个新的流水记录
//	@Insert("insert into credit(userId,amount,leftAmount,type,startTime,endTime) values(#{userId},#{amount},#{amount},1,#{startTime},#{endTime})")
//	//@Insert("insert into credit(leftAmount) values(1)")
//	@Options(useGeneratedKeys = true, keyProperty = "creditId", keyColumn = "creditId")
//	public int addCredit(Credit credit);
	//创建流水
	@Insert("insert into credit(userId,amount,leftAmount,type,startTime,endTime) values(#{userId},#{amount},#{amount},#{type},#{startTime},#{endTime})")
	@Options(useGeneratedKeys = true, keyProperty = "creditId", keyColumn = "creditId")
	public int saveCredit(Credit credit);
	
	
	//减少积分,注意在service中应该检查积分是否足够
	//这里只提供原子操作
	//减少积分只能减少有效期内的积分
	@Update("update credit set leftAmount=leftAmount-#{minusAmount} where userId=#{userId}")
	public int minusCredit(Credit credit, Integer minusAmount);
	
	//业务需要的减少积分方式：使用全部积分
	@Update("update credit set leftAmount=0 where userId=#{userId} and endTime>#{nowTime}")
	public int zeroCredit(String userId, String nowTime);
	
	//查询可用积分
	@Select("select sum(leftAmount) from credit where userId=#{userId} and endTime>#{nowTime} and type=1")
	public int getUsableCredit(@Param("userId") String userId, @Param("nowTime") String nowTime);
	
	//查询积分流水
	@Select("select * from credit where userId=#{userId} order by startTime desc")
	public List<Credit> getCreditTransaction(String userId);
	
}
